import { COMPLETE, FAILURE, RUNNING, SUCCESS } from '../constants';
import BaseNode from '../core/BaseNode';
import Tick from '../core/Tick';
import Picker from './Picker';

/**
 * 执行体,忽略非Error和Finish,剩余全都忽略
 */
export default class Executor extends Picker {

    private runTag: boolean = false
    private taskQueue: Array<Function> = new Array()

    get isRunning() {
        return this.runTag
    }

    run(call: Function) {
        if (this.runTag) {
            this.taskQueue.push(call)
            return;
        }
        call()
    }

    // 默认的状态实现
    protected defaultStatus(): number {
        return COMPLETE
    }

    // 判断需要忽略的状态
    protected isIgnore(status: number): boolean {
        return status === SUCCESS || status === FAILURE || status === RUNNING
    }

    /**
     * 慎重使用,最好是只用在非Mem...的对象中,否则容易出现越界.
     */
    removeChild(child: BaseNode) {
        this.children.splice(this.children.indexOf(child), 1)
    }

    onEnter(tick: Tick, ...args: any[]): void {
        let call = this.taskQueue.shift()
        while (call) {
          call()
          call = this.taskQueue.shift()
        }
        this.runTag = true;
    }


    onExit(tick: Tick, status: number, ...args: any[]): void {
        this.runTag = false;
    }
};